<template>
  <div>
    <!-- 分类列表 -->
    <el-card>
      <Category :flag="isAddorEdit"></Category>
    </el-card>

    <!-- 平台属性 -->
    <el-card style="margin-top: 20px" v-if="!isAddorEdit">
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="gotoAddOrEdit"
        :disabled="!category3Id"
        >添加属性</el-button
      >
      <el-table
        v-loading="loading"
        :data="attrList"
        border
        style="margin-top: 20px"
      >
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column label="属性名称" prop="attrName"></el-table-column>
        <el-table-column label="属性值名称列表">
          <template slot-scope="{ row }">
            <el-tag
              type="success"
              v-for="attrValue in row.attrValueList"
              :key="attrValue.id"
              style="margin-right: 10px"
              >{{ attrValue.valueName }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <el-button
              type="warning"
              icon="el-icon-edit-outline"
              @click="gotoAddOrEdit(row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="deleteAttr(row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加或者-------------------------------------------修改 -->
    <el-card style="margin-top: 20px" v-else>
      <el-form inline>
        <el-form-item label="属性名">
          <el-input
            v-model="formData.attrName"
            clearable
            @change="attrNameIsRepeat"
          ></el-input>
        </el-form-item>
      </el-form>

      <el-button
        type="primary"
        :disabled="!formData.attrName.length"
        @click="addAttrValue"
        >添加属性值</el-button
      >
      <el-button @click="gotoList">取消</el-button>

      <el-table
        v-loading="loading"
        :data="formData.attrValueList"
        style="margin-top: 20px"
        border
      >
        <el-table-column label="序号" type="index" width="80"></el-table-column>

        <!-- element-ui第二列有时候作用域插槽拿不到值，必须换一列  -->
        <el-table-column label="" width="0"></el-table-column>
        <el-table-column label="属性值名字">
          <template slot-scope="{ row }">
            <el-input
              v-model="row.valueName"
              v-if="row.isEdit"
              @blur="blurHandler(row)"
              ref="valueNameInput"
            ></el-input>
            <span v-else @dblclick="changeValueName(row)">{{
              row.valueName
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{ row, $index }">
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="deleteAttrValue($index)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="margin-top: 20px">
        <el-button
          type="primary"
          @click="addOrEdit"
          :disabled="!formData.attrValueList.length"
          >保存</el-button
        >
        <el-button @click="gotoList">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { cloneDeep } from "@/utils/cloneDeep";
import {
  reqAttrData,
  reqAddOrEditAttr,
  reqDeleteAttr,
} from "@/api/platformAttr";
export default {
  name: "platformAttr",
  data() {
    return {
      attrList: [],
      loading: false,
      isAddorEdit: false,
      attrValueName: "",
      formData: {
        // 添加的属性名
        attrName: "",
        // 属性值名
        attrValueList: [],
        // 3Id
        categoryId: 0,
        // 固定的
        categoryLevel: 3,
      },
    };
  },
  computed: {
    ...mapState({
      category1Id: (state) => state.category.category1Id,
      category2Id: (state) => state.category.category2Id,
      category3Id: (state) => state.category.category3Id,
    }),
  },

  // 监听3ID的变化，看看有没有选择最后的那个选项
  watch: {
    category3Id: {
      handler() {
        this.getAttrList();
      },
      immediate: true,
    },
  },

  mounted() {},

  methods: {
    // 跳转回首页
    gotoList() {
      this.isAddorEdit = false;
    },

    // 添加或编辑页面
    gotoAddOrEdit(row) {
      this.loading = true;
      this.isAddorEdit = true;
      if (row.id) {
        // 编辑,数据回显
        this.formData = cloneDeep(row);
        // 不可以直接设置isEdit，因为直接设置的isEdit不是响应式的，页面不会更新
        this.formData.attrValueList.forEach((item) =>
          this.$set(item, "isEdit", false)
        );
      } else {
        // 添加页面
        this.formData = {
          // 添加的属性名
          attrName: "",
          // 属性值名
          attrValueList: [],
          // 3Id
          categoryId: 0,
          // 固定的
          categoryLevel: 3,
        };
      }
      this.loading = false;
    },

    //判断属性名是否重复
    attrNameIsRepeat() {
      // 遍历数组，判断是否有同名属性，使用some
      const flag = this.attrList.some(
        (item) => item.attrName == this.formData.attrName
      );
      if (flag) {
        // 如果有同名属性，就清空输入框并提示错误
        this.formData.attrName = "";
        this.$message.error("该属性名已存在");
      }
    },

    // 获取属性列表的数据
    async getAttrList() {
      this.loading = true;
      // 从category仓库中拿到所有的ID，监听category3ID的变化，只要发生变化了就重新发送请求获取平台属性的数据
      // 判断3ID为不为空，不为空就发请求
      // 3ID改变时清空列表
      this.attrList = [];
      if (this.category3Id !== "") {
        try {
          const res = await reqAttrData(
            this.category1Id,
            this.category2Id,
            this.category3Id
          );
          this.attrList = res.data;
          // this.$message.success("获取属性列表数据成功");
        } catch (error) {
          console.log(error);
          this.$message.error("获取属性列表数据失败");
        }
      }
      this.loading = false;
    },

    // 添加属性值
    addAttrValue() {
      // 给属性值列表添加属性
      this.formData.attrValueList.push({
        // 添加一个空属性
        valueName: "",
        // 定义一个编辑状态的数据
        isEdit: true,
      });

      // 添加焦点给input,不可以直接聚焦，因为拿不到dom，需要等页面刷新过后,使用nextTick可以等页面刷新过后再调用focus
      this.$nextTick(() => {
        this.$refs.valueNameInput?.focus();
      });
    },

    // 添加或修改属性，保存
    async addOrEdit() {
      this.formData.categoryId = Number(this.category3Id);
      // 无论是添加或者是编辑用的都是同一个请求，直接发送
      console.log(this.formData);
      try {
        await reqAddOrEditAttr(this.formData);
        this.$message.success(
          this.formData.id ? "编辑属性成功" : "添加属性成功"
        );
        // 添加成功以后跳转回首页
        this.gotoList();
        await this.getAttrList();
      } catch (error) {
        console.log(error);
      }
    },

    //属性值输入框失去焦点时触发
    blurHandler(row) {
      // 校验一下，不能为空，为空的话直接去除这个对象
      if (!row.valueName) {
        this.formData.attrValueList.splice(
          this.formData.attrValueList.length - 1,
          1
        );
      } else {
        row.isEdit = false;
      }
    },

    // 双击修改属性值
    changeValueName(row) {
      row.isEdit = true;
      // 获取焦点
      // 添加焦点给input,不可以直接聚焦，因为拿不到dom，需要等页面刷新过后,使用nextTick可以等页面刷新过后再调用focus
      this.$nextTick(() => {
        this.$refs.valueNameInput?.focus();
      });
    },

    // 删除属性值
    deleteAttrValue(index) {
      this.formData.attrValueList.splice(index, 1);
    },

    // 删除整条属性
    deleteAttr(row) {
      this.$confirm("是否确定删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "danger",
        callback: async (action) => {
          // 如果点击了确定按钮
          if (action == "confirm") {
            try {
              await reqDeleteAttr(row.id);
              this.$message.success("删除成功");
              // 重新获取数据
              this.getAttrList();
            } catch (error) {
              console.log(error);
              this.$message.error("删除失败");
            }
          }
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped></style>
